// utils/syntaxDiagramManager.ts
import { convertEbnfToDiagram } from './syntaxDiagram';

interface DiagramCache {
  [key: string]: {
    html: string;
    hash: string;
    timestamp: number;
  };
}

class SyntaxDiagramManager {
  private cache: DiagramCache = {};
  private prebuiltDiagrams: Record<string, { html: string; hash: string }> = {};
  private cacheExpiry = 24 * 60 * 60 * 1000; // 24小时

  constructor() {
    this.loadPrebuiltDiagrams();
  }

  // 加载预构建的图表
  private async loadPrebuiltDiagrams() {
    try {
      const response = await fetch('/syntax-diagrams/index.json');
      if (response.ok) {
        this.prebuiltDiagrams = await response.json();
        console.log(`Loaded ${Object.keys(this.prebuiltDiagrams).length} prebuilt diagrams`);
      }
    } catch (error) {
      console.warn('Failed to load prebuilt diagrams:', error);
    }
  }

  // 生成缓存键
  private generateCacheKey(ebnf: string): string {
    return btoa(ebnf).replace(/[^a-zA-Z0-9]/g, '').substring(0, 16);
  }

  // 检查缓存
  private getFromCache(ebnf: string): string | null {
    const key = this.generateCacheKey(ebnf);
    const cached = this.cache[key];
    
    if (cached && Date.now() - cached.timestamp < this.cacheExpiry) {
      return cached.html;
    }
    
    return null;
  }

  // 添加到缓存
  private addToCache(ebnf: string, html: string) {
    const key = this.generateCacheKey(ebnf);
    this.cache[key] = {
      html,
      hash: this.generateCacheKey(ebnf),
      timestamp: Date.now()
    };
  }

  // 查找预构建的图表
  private findPrebuiltDiagram(ebnf: string): string | null {
    const ebnfHash = this.generateCacheKey(ebnf);
    
    for (const [id, diagram] of Object.entries(this.prebuiltDiagrams)) {
      if (diagram.hash === ebnfHash) {
        return diagram.html;
      }
    }
    
    return null;
  }

  // 主转换方法 - 添加参数验证
  async convertEbnfToDiagram(ebnf: string): Promise<string> {
    // 添加参数验证
    if (!ebnf) {
      console.warn('EBNF content is empty or undefined');
      return '';
    }

    if (typeof ebnf !== 'string') {
      console.warn('EBNF content must be a string, got:', typeof ebnf);
      return '';
    }

    if (!ebnf.trim()) {
      console.warn('EBNF content is empty after trimming');
      return '';
    }

    // 1. 检查缓存
    const cached = this.getFromCache(ebnf);
    if (cached) {
      return cached;
    }

    // 2. 检查预构建图表
    const prebuilt = this.findPrebuiltDiagram(ebnf);
    if (prebuilt) {
      this.addToCache(ebnf, prebuilt);
      return prebuilt;
    }

    // 3. 客户端生成
    try {
      const html = await convertEbnfToDiagram(ebnf);
      this.addToCache(ebnf, html);
      return html;
    } catch (error) {
      console.error('Failed to generate diagram:', error);
      return '';
    }
  }

  // 清理过期缓存
  cleanupCache() {
    const now = Date.now();
    for (const [key, cached] of Object.entries(this.cache)) {
      if (now - cached.timestamp > this.cacheExpiry) {
        delete this.cache[key];
      }
    }
  }

  // 获取缓存统计
  getCacheStats() {
    return {
      cached: Object.keys(this.cache).length,
      prebuilt: Object.keys(this.prebuiltDiagrams).length
    };
  }
}

// 创建全局实例
export const syntaxDiagramManager = new SyntaxDiagramManager();

// 定期清理缓存
if (typeof window !== "undefined") {
  setInterval(() => {
    syntaxDiagramManager.cleanupCache();
  }, 60 * 60 * 1000); // 每小时清理一次
}